import {queryEmp, queryEmployeeRole, queryRole, remove, resetPwd, saveEmployeeRole, saveOrUpdate} from './service';

export default {
  namespace: 'employee',
  state: {
    data: {},
    pagination: {},
    loading: true,
    searchWhere: {},
    roleData:{rows:[]}
  },

  effects: {
    * fetch({payload}, {select, call, put}) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const employee = yield select(state => state.employee);
      if (!payload) {
        payload = {};
      }
      payload = employee.searchWhere;
      //对象的合并 Object.assign(payload, pagination)----->Object.assign(目标对象, 被合并的对象) 如果目标对象与被合并对象有相同的属性变量，目标对象中属性值会被覆盖
      Object.assign(payload, employee.pagination);
      const response = yield call(queryEmp, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    * add({payload, callback}, {call, put}) {
      const response = yield call(saveOrUpdate, payload);
      yield put({type: 'fetch'});
      if (callback) callback(response);
    },
    * edit({payload, callback}, {call, put}) {
      const response = yield call(saveOrUpdate, payload);
      yield put({type: 'fetch'});
      if (callback) callback(response);
    },
    * remove({payload, callback}, {call, put}) {
      const response = yield call(remove, payload);
      yield put({type: 'fetch'});
      if (callback) callback(response);
    },
    * resetPwd({payload, callback}, {call, put}) {
      const response = yield call(resetPwd, payload);
      yield put({type: 'fetch'});
      if (callback) callback(response);
    },

    *queryRole({ payload }, { call, put }) {
      const response = yield call(queryRole, payload);
      if(response.resultCode==="1") {
        yield put({
          type: 'saveRole',
          payload: response,
        });
      }
    },
    *queryEmployeeRole({ payload, callback }, { call }) {
      const response = yield call(queryEmployeeRole, payload);
      if (callback) callback(response);
    },
    *saveEmployeeRole({ payload, callback }, { call, put }) {
      const response = yield call(saveEmployeeRole, payload);
      yield put({type: 'fetch'});
      if (callback) callback(response);
    },
  },
  reducers: {
    saveRole(state, action) {
      return {
        ...state,
        roleData: action.payload,
      };
    },
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },

  },
};
